package com.soft.mainsite.module.staticresource.web;

import com.soft.mainsite.common.exception.SystemException;
import com.soft.mainsite.common.utils.JsonUtil;
import com.soft.mainsite.module.staticresource.entity.StaticResourceFile;
import com.soft.mainsite.module.staticresource.service.StaticResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * FileManagementController此类用于文件夹增删改查，图片，视频，JS,CSS文件上传，替换，删除，文件名查看。
 *
 * @author: hujm
 * @date: 2019年08月29日 14:42
 * @remark:
 */
@Slf4j
@Controller
@RequestMapping("/staticResource")
public class StaticResourceController {

    @Autowired
    private StaticResourceService staticResourceService;

    @RequestMapping
    public String index(Model model) {
        List<StaticResourceFile> list = staticResourceService.findAll();
        model.addAttribute("staticResourceFileList", list);
        return "staticResource/static_resource";
    }

    @RequestMapping("/input")
    public String input(StaticResourceFile staticResourceFile, Model model){
        if (staticResourceFile.getFilePath() == null){
            throw new SystemException("静态资源路径不能为空！");
        }
        model.addAttribute("staticResourceFile", staticResourceService.findByPath(staticResourceFile.getFilePath()));
        return "staticResource/static_resource_input";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("files") MultipartFile[] files, @RequestParam("currentPath") String currentPath){
        if (files.length < 1){
            return JsonUtil.toError("文件为空，请选择后重新上传！");
        }
        staticResourceService.upload(files, currentPath);
        return JsonUtil.toSuccess("静态资源上传成功！", "static-resource-tab", false);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam("filePath") String filePath){
        if (filePath == null){
            throw new SystemException("静态资源路径错误！");
        }
        staticResourceService.deleteByPath(filePath);
        return JsonUtil.toSuccess("删除成功！","static-resource-tab", false);
    }
}
